package com.wangmin.intercept.websetting;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.wangmin.intercept.listener.IWebView;
import com.wangmin.intercept.utils.LogUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;



/**
 * Created by wm on 2016/11/11.
 */
public class CustomWebview extends WebView implements IWebView {
    private static boolean mBoMethodsLoaded = false;

    private static Method mOnPauseMethod = null;
    private static Method mOnResumeMethod = null;
    private static Method mSetFindIsUp = null;
    private static Method mNotifyFindDialogDismissed = null;
    private CustomWebChromeClient videoEnabledWebChromeClient;
    private boolean addedJavascriptInterface;
    private boolean loadAd = true;
    public CustomWebview(Context context) {
        this(context,null);
    }

    public CustomWebview(Context context, AttributeSet attrs) {
        super(context,attrs);
        init(context);
    }

    public CustomWebview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void init(Context context){
        setBackgroundColor(0);
        WebSettings webSettings = getSettings();
        webSettings.setBuiltInZoomControls(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setUseWideViewPort(true);
        try{
            Method method = webSettings.getClass().getMethod("setPluginsEnabled",boolean.class);
            method.invoke(webSettings,true);
        }catch (Exception e){
            LogUtils.getNewInstance("setPluginsEnabled").eob("出现异常"+(e==null?"":e.getMessage()));
        }
        webSettings.setPluginState(WebSettings.PluginState.ON);
        //启用数据库
        webSettings.setDatabaseEnabled(false);
        //设置定位的数据库路径
        String dir = context.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setGeolocationDatabasePath(dir);
        //启用地理定位
        webSettings.setGeolocationEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        if(Build.VERSION.SDK_INT <= 18){
            webSettings.setSavePassword(false);
        }
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setSaveFormData(true);
        //开启DomStorage缓存
        webSettings.setDomStorageEnabled(false);
        if(Build.VERSION.SDK_INT >= 21){
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setSupportMultipleWindows(false);
        setHorizontalScrollBarEnabled(false);
        setVerticalScrollBarEnabled(false);
        if (Build.VERSION.SDK_INT < 21) {
            CookieSyncManager.getInstance().sync();
        } else {
            CookieManager.getInstance().flush();
        }
        addedJavascriptInterface = false;
        final String USER_AGENT_STRING = webSettings.getUserAgentString() + " Rong/2.0";
        webSettings.setUserAgentString( USER_AGENT_STRING );
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        loadMethods();
//        context.registerReceiver(receiver, filter);
    }
    public boolean isVideoFullscreen()
    {
        return videoEnabledWebChromeClient != null && videoEnabledWebChromeClient.isVideoFullscreen();
    }

    @Override
    public void setOnLongClickListener(OnLongClickListener l) {
        super.setOnLongClickListener(l);
    }

    @Override
    public void setLoadAd(boolean loadAd) {
        this.loadAd = loadAd;
    }

    @Override
    public boolean isloadAd() {
        return loadAd;
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    public void setWebChromeClient(WebChromeClient client)
    {
        if (client instanceof CustomWebChromeClient)
        {
            this.videoEnabledWebChromeClient= (CustomWebChromeClient) client;
        }
        super.setWebChromeClient(client);
    }

    @Override
    public void loadData(String data, String mimeType, String encoding)
    {
        addJavascriptInterface();
        super.loadData(data, mimeType, encoding);
    }

    @Override
    public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)
    {
        addJavascriptInterface();
        super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
    }

    @Override
    public void loadUrl(String url)
    {
        addJavascriptInterface();
        super.loadUrl(url);
    }

    @Override
    public void loadUrl(String url, Map<String, String> additionalHttpHeaders)
    {
        addJavascriptInterface();
        super.loadUrl(url, additionalHttpHeaders);
    }

    private void addJavascriptInterface()
    {
        if (!addedJavascriptInterface)
        {
            addedJavascriptInterface = true;
        }
    }



    IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(reference);
            Cursor cursor = downloadManager.query(query);
            if(cursor.moveToNext()){

            }
        }
    };

    /**
     * Perform an 'onPause' on this WebView through reflexion.
     */
    public void doOnPause() {
        if (mOnPauseMethod != null) {
            try {
                mOnPauseMethod.invoke(this);
            } catch (IllegalArgumentException e) {
                Log.e("CustomWebView", "doOnPause(): " + e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e("CustomWebView", "doOnPause(): " + e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e("CustomWebView", "doOnPause(): " + e.getMessage());
            }
        }
    }

    /**
     * Perform an 'onResume' on this WebView through reflexion.
     */
    public void doOnResume() {
        if (mOnResumeMethod != null) {
            try {

                mOnResumeMethod.invoke(this);

            } catch (IllegalArgumentException e) {
                Log.e("CustomWebView", "doOnResume(): " + e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e("CustomWebView", "doOnResume(): " + e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e("CustomWebView", "doOnResume(): " + e.getMessage());
            }
        }
    }

    public void doSetFindIsUp(boolean value) {
        if (mSetFindIsUp != null) {
            try {

                mSetFindIsUp.invoke(this, value);

            } catch (IllegalArgumentException e) {
                Log.e("CustomWebView", "doSetFindIsUp(): " + e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e("CustomWebView", "doSetFindIsUp(): " + e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e("CustomWebView", "doSetFindIsUp(): " + e.getMessage());
            }
        }
    }
    /**
     * Load static reflected methods.
     */
    private void loadMethods() {
        if (!mBoMethodsLoaded) {
            try {
                mOnPauseMethod = WebView.class.getMethod("onPause");
                mOnResumeMethod = WebView.class.getMethod("onResume");
            } catch (SecurityException e) {
                Log.e("CustomWebView", "loadMethods(): " + e.getMessage());
                mOnPauseMethod = null;
                mOnResumeMethod = null;
            } catch (NoSuchMethodException e) {
                Log.e("CustomWebView", "loadMethods(): " + e.getMessage());
                mOnPauseMethod = null;
                mOnResumeMethod = null;
            }

            try {

                mSetFindIsUp = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
                mNotifyFindDialogDismissed = WebView.class.getMethod("notifyFindDialogDismissed");

            } catch (SecurityException e) {
                Log.e("CustomWebView", "loadMethods(): " + e.getMessage());
                mSetFindIsUp = null;
                mNotifyFindDialogDismissed = null;
            } catch (NoSuchMethodException e) {
                Log.e("CustomWebView", "loadMethods(): " + e.getMessage());
                mSetFindIsUp = null;
                mNotifyFindDialogDismissed = null;
            }

            mBoMethodsLoaded = true;
        }
    }

}
